package com.hs.service.impl;

import com.hs.entity.LoginUser;
import com.hs.entity.User;
import com.hs.service.LoginService;
import com.hs.util.JwtUtil;
import com.hs.util.RedisCache;
import com.hs.util.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

/**
 * @author fuyanru
 * @date 2024年05月02日 20:27
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;
    @Override
    public ResponseResult login(User user) {
        // 调用AuthenticationManager的authenticate进行身份认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
         // 如果认证没有通过，抛出异常
        if(Objects.isNull(authenticate)){
            throw  new RuntimeException("用户名或密码错误");
        }
        //认证通过，使用userid生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);

        // 把完整的用户信息存入redis，userid作为key【为避免重复，可以添加一些前缀】
        redisCache.setCacheObject("login:"+userId,loginUser);
        //把token响应给前端
        HashMap<Object, String> map = new HashMap<>();
        map.put("token",jwt);
        return new ResponseResult<>(200,"登录成功！",map);
    }
    @Override
    public ResponseResult logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String userid = loginUser.getUser().getId().toString();
        redisCache.deleteObject("login:" +userid);
        return new ResponseResult<>(200,"注销成功！");
    }
}
